<template>
<div>
  <!-- 查询条件表单 -->
  <div style="margin-bottom: 20px;">
    <el-form inline>
      <el-form-item label="商品名称">
        <el-input v-model="searchConditions.productName" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品 ID">
        <el-input v-model="searchConditions.productId" placeholder="请输入商品 ID" type="number"></el-input>
      </el-form-item>
<!--      <el-form-item label="分类 ID">-->
<!--        <el-input v-model="searchConditions.categoryId" placeholder="请输入分类 ID" type="number"></el-input>-->
<!--      </el-form-item>-->
      <el-form-item label="分类" class="custom-form-item">
        <el-tree-select
          v-model="searchConditions.categoryId"
          :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
          :data="categoryStore.categories"
          :render-after-expand="false"
          style="width: 240px"
        >
          <template #default="{ data: { categoryName } }">
            {{ categoryName }}
          </template>
        </el-tree-select>
      </el-form-item>
      <el-form-item label="价格区间">
        <el-col :span="11">
          <el-input v-model="searchConditions.minPrice" placeholder="最低价格" type="number"></el-input>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-input v-model="searchConditions.maxPrice" placeholder="最高价格" type="number"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="searchConditions.updateTime"
          type="datetime"
          placeholder="选择更新时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DDTHH:mm:ss"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="fetchProductListWithConditions">刷新商品列表</el-button>
    <el-button type="primary" @click="editProduct2()">添加商品</el-button>
    <el-button type="primary" @click="fetchProductListWithConditions">查询</el-button>
    <el-button @click="resetSearchConditions">重置</el-button>
  </div>

  <!-- 商品表格 -->
  <el-table
    :data="tableData"
    row-key="id"
    :default-expand-all="false"
    style="width: 100%"
    height="600"
  >
    <el-table-column label="商品 ID" prop="productId" />
    <el-table-column label="商品图">
      <template #default="scope">
        <el-image style="width: 100px; height: 100px" :src="scope.row.imageUrl" fit="contain" />
      </template>
    </el-table-column>
    <el-table-column label="商品名称" prop="name" />
    <el-table-column label="分类 ID" prop="categoryId" />
    <el-table-column label="总数量" prop="quantity" />
<!--    <el-table-column label="售卖数量" prop="buyNum" />-->
    <el-table-column label="商品描述" prop="description" />
    <el-table-column label="适用年龄" prop="applyAge" />
    <el-table-column label="价格" prop="price" />
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <el-button type="text" @click="editProduct(scope.row)">修改</el-button>
        <el-button type="text" @click="deleteProduct(scope.row)">删除</el-button>
        <el-button type="text" @click="showAttributes(scope.row.productId)">查看属性</el-button>
      </template>
    </el-table-column>
    <el-table-column label="修改时间">
      <template #default="scope">
        {{ formatDate(scope.row.updatedAT) }}
      </template>
    </el-table-column>
    <el-table-column label="创建时间">
      <template #default="scope">
        {{ formatDate(scope.row.createdAt) }}
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <div class="pagination-container">
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 商品修改弹出层 -->
  <el-drawer v-model="productDialogVisible" :title="isProductSave ? '添加商品' : '修改商品'" direction="ltr">
    <el-form :model="currentProduct" class="custom-form" label-width="auto">
      <el-form-item label="商品名称" class="custom-form-item">
        <el-input v-model="currentProduct.name" class="custom-input"></el-input>
      </el-form-item>
      <el-form-item v-show="!isProductSave" label="价格" class="custom-form-item">
        <el-input v-model="currentProduct.price" class="custom-input"></el-input>
      </el-form-item>
      <el-form-item label="分类" class="custom-form-item">
        <el-tree-select
          v-model="currentProduct.categoryId"
          :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
          :data="categoryStore.categories"
          :render-after-expand="false"
          style="width: 240px"
        >
          <template #default="{ data: { categoryName } }">
            {{ categoryName }}
          </template>
        </el-tree-select>
      </el-form-item>
      <el-form-item label="描述" class="custom-form-item">
        <el-input v-model="currentProduct.description" class="custom-input"></el-input>
      </el-form-item>
      <el-form-item label="详细描述" class="custom-form-item">
        <el-input v-model="currentProduct.detailInfo" class="custom-input"></el-input>
      </el-form-item>
      <el-form-item v-show="!isProductSave" label="商品图" class="custom-form-item">
        <list-upload ref="listUpload" :current-product-id="currentProductId"></list-upload>
      </el-form-item>
      <el-form-item v-show="!isProductSave" label="属性" class="custom-form-item">
        <div>
          <el-tag type="primary" v-for="a1 in attributesData" style="margin: 2px">
            {{ a1.attributeName }}
          </el-tag>
        </div>
        <el-button type="text" @click="showAttributes(currentProductId)">查看属性</el-button>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="productDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveProduct">保存</el-button>
    </div>
  </el-drawer>

  <!-- 商品属性弹出层 -->
  <el-drawer v-model="attributesDrawerVisible" title="商品属性" direction="rtl" size="50%">
    <el-table :data="attributesData" style="width: 100%" height="700">
      <el-table-column label="属性ID" prop="attributeId" />
      <el-table-column label="属性名称" prop="attributeName" />
      <el-table-column label="图片" prop="attributeImg">
        <template #default="scope">
          <img :src="scope.row.attributeImg" style="width: 50px; height: 50px;">
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="price" />
      <el-table-column label="数量" prop="quantity" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="text" @click="editAddAttributeDrawer(scope.row)">修改</el-button>
          <el-button type="text" @click="deleteAttribute(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer v-model="attributeEditDrawerVisible" title="属性管理" direction="rtl" :append-to-body="true">
      <el-form :model="currentAttribute" class="custom-form" label-width="auto">
        <el-form-item label="属性名称">
          <el-input v-model="currentAttribute.attributeName" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:8081/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="currentAttribute.attributeImg" :src="currentAttribute.attributeImg" class="avatar" width="300px" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="currentAttribute.price" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="currentAttribute.quantity" class="custom-input"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: right; margin-top: 20px;">
        <el-button @click="attributeEditDrawerVisible = false">取消</el-button>
        <el-button type="primary" @click="selectAttribute">保存</el-button>
      </div>
    </el-drawer>
    <div style="text-align: right; margin-top: 20px;">
      <el-button type="primary" @click="openAddAttributeDrawer">新增属性</el-button>
    </div>
  </el-drawer>
</div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { useCategoryStore } from '@/stores/categoryStore';
import {
  getBrandProductsWithConditions,
  updateProduct,
  getAttributes,
  saveAttribute,
  putAttribute,
  uploadFile,
  getProductResourcesByProductId,
  createProductResource,
  createProduct
} from '@/common/net/api';
import type {
  BaseResponse,
  Product,
  ProductVO,
  AttributeProduct,
  PageResult,
  AttributeProduct2
} from "@/common/types/productTypes";
import ListUpload from "@/components/listUpload.vue";

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref<Product[]>([]);
const categoryStore = useCategoryStore();
const searchConditions = ref({
  productName: '',
  productId: null,
  categoryId: null,
  minPrice: null,
  maxPrice: null,
  updateTime: null,
});

const fetchProductListWithConditions = async () => {
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      productName: searchConditions.value.productName,
      productId: searchConditions.value.productId,
      categoryId: searchConditions.value.categoryId,
      minPrice: searchConditions.value.minPrice,
      maxPrice: searchConditions.value.maxPrice,
      updateTime: searchConditions.value.updateTime,
    };
    await getBrandProductsWithConditions(params).then(res => {
      tableData.value = res.data.records || [];
      total.value = res.data.total || 0;
    });
  } catch (error) {
    ElMessage.error('获取商品列表失败');
  }
};

const resetSearchConditions = () => {
  searchConditions.value = {
    productName: '',
    productId: null,
    categoryId: null,
    minPrice: null,
    maxPrice: null,
    updateTime: null,
  };
  fetchProductListWithConditions();
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchProductListWithConditions();
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchProductListWithConditions();
};

const formatDate = (dateString: any) => {
  return moment(dateString).format('YYYY/MM/DD HH:mm:ss');
};

// 商品修改弹出层
const productDialogVisible = ref(false);
const currentProduct = ref<Product>();
let currentProductId = ref(0);
const isProductSave = ref(false);

const editProduct2 = () => {
  isProductSave.value = true;
  currentProduct.value = {
    name: '',
    categoryId: 0,
    description: '',
    detailInfo: '',
    applyAge: '',
    version: 0
  };
  productDialogVisible.value = true;
};

const editProduct = (product: Product) => {
  currentProduct.value = { ...product };
  currentProductId.value = product.productId;
  getAttributes(currentProductId.value).then(res => {
    attributesData.value = res.data || [];
  });
  productDialogVisible.value = true;
};

const saveProduct = async () => {
  if (isProductSave.value) {
    await createProduct(currentProduct.value).then(res => {
      if (res.data.state) {
        ElMessage.success('商品添加成功');
        productDialogVisible.value = false;
        fetchProductListWithConditions();
      } else {
        ElMessage.error('添加商品失败');
      }
    });
  } else {
    await updateProduct(currentProduct.value).then(res => {
      if (res.data.state) {
        ElMessage.success('商品修改成功');
        productDialogVisible.value = false;
        fetchProductListWithConditions();
      } else {
        ElMessage.error('修改商品失败');
      }
    });
  }
};

const deleteProduct = async (product: Product) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '删除商品', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    product.isDel = 1;
    try {
      await updateProduct(product).then(res => {
        if (res.data.state) {
          ElMessage.success('删除成功');
          fetchProductListWithConditions();
        } else {
          ElMessage.error('删除失败');
        }
      });
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

const attributesData = ref<AttributeProduct[]>([]);
const attributesDrawerVisible = ref(false);
const attributeEditDrawerVisible = ref(false);
const currentAttribute = ref<AttributeProduct>({
  attributeName: '',
  attributeImg: '',
  productId: currentProductId.value,
  price: 0,
  quantity: 0,
});
const isEdit = ref(0);

const openAddAttributeDrawer = () => {
  isEdit.value = 0;
  currentAttribute.value = {
    productId: currentProductId.value,
    attributeName: '',
    attributeImg: '',
    price: 0,
    quantity: 0,
  };
  attributeEditDrawerVisible.value = true;
};

const editAddAttributeDrawer = (attribute: AttributeProduct) => {
  isEdit.value = 1;
  currentAttribute.value = attribute;
  attributeEditDrawerVisible.value = true;
};

const showAttributes = async (productId: any) => {
  currentProductId.value = productId;
  try {
    await getAttributes(productId).then(res => {
      attributesData.value = res.data || [];
      attributesDrawerVisible.value = true;
    });
  } catch (error) {
    ElMessage.error('获取商品属性失败');
  }
};

const selectAttribute = () => {
  if (isEdit.value) {
    editAttribute();
  } else {
    addAttribute();
  }
};

const editAttribute = async () => {
  try {
    await putAttribute(currentAttribute.value).then(res => {
      if (res.data.state) {
        ElMessage.success('属性修改成功');
        attributeEditDrawerVisible.value = false;
        showAttributes(currentAttribute.value.productId);
      } else {
        ElMessage.error('修改属性失败');
      }
    });
  } catch (error) {
    ElMessage.error('修改属性失败');
  }
};

const addAttribute = async () => {
  try {
    await saveAttribute(currentAttribute.value).then(res => {
      ElMessage.success('属性添加成功');
      attributeEditDrawerVisible.value = false;
      showAttributes(currentAttribute.value.productId);
    });
  } catch (error) {
    ElMessage.error('添加属性失败');
  }
};

const deleteAttribute = async (attribute: AttributeProduct) => {
  ElMessageBox.confirm('确定要删除该属性吗？', '删除属性', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    attribute.isDel = 1;
    await putAttribute(attribute).then(res => {
      if (res.data.state) {
        ElMessage.success('属性删除成功');
        attributeEditDrawerVisible.value = false;
        showAttributes(attribute.productId);
      } else {
        ElMessage.error('删除失败');
      }
    });
  });
};

const handleAvatarSuccess = (response: any) => {
  currentAttribute.value.attributeImg = response.data;
};

onMounted(() => {
  fetchProductListWithConditions();
});
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin: 10px 0;
}
</style>
